package com.jhgsys.internal.hazard.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jhgsys.internal.base.dto.BaseAreaSchedulingDto;
import com.jhgsys.internal.base.entity.BaseUserScoreRecord;
import com.jhgsys.internal.base.service.IBaseAreaSchedulingService;
import com.jhgsys.internal.base.service.IBaseUserScoreRecordService;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.hazard.constant.HazardConstant;
import com.jhgsys.internal.hazard.dto.HazardReportDto;
import com.jhgsys.internal.hazard.dto.HazardReportMessageDto;
import com.jhgsys.internal.hazard.entity.*;
import com.jhgsys.internal.hazard.mapper.HazardReportMapper;
import com.jhgsys.internal.hazard.service.*;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.system.dto.TenantDto;
import com.jhgsys.internal.system.entity.Dept;
import com.jhgsys.internal.system.entity.Tenant;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IDeptService;
import com.jhgsys.internal.system.service.ITenantService;
import com.jhgsys.internal.system.service.IUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 隐患上报 Service实现
 *
 * @author wanghw
 * @date 2024-08-20 09:23:04
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class HazardReportServiceImpl extends ServiceImpl<HazardReportMapper, HazardReport> implements IHazardReportService {

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IDeptService deptService;


    @Autowired
    private IHazardReportFileService fileService;

    @Autowired
    private IHazardReportAuditRecordService auditRecordService;

    @Autowired
    private IHazardTypeOperationService hazardTypeOperationService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBaseUserScoreRecordService baseUserScoreRecordService;

    @Autowired
    private IHazardReportMessageService hazardReportMessageService;

    @Autowired
    private IBaseAreaSchedulingService schedulingService;

    @Autowired
    private IHazardReportAreaUserService reportAreaUserService;





    /**
     * 查询（分页）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     * @param request QueryRequest
     * @param hazardReport hazardReport
     * @return IPage<HazardReport>
    */
    @Override
    public IPage<HazardReportDto> findHazardReportPage(QueryRequest request, HazardReportDto hazardReport) {
        LambdaQueryWrapper<HazardReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HazardReport::getDeletedFlg, 0);
        if(StringUtils.isNotBlank(hazardReport.getTenantId())){
            queryWrapper.eq(HazardReport::getTenantId,hazardReport.getTenantId());
        }
        if(StringUtils.isNotBlank(hazardReport.getStatus())){
            if(hazardReport.getStatus().indexOf(StringPool.COMMA)>-1){
                queryWrapper.in(HazardReport::getStatus,Arrays.asList(hazardReport.getStatus().split(StringPool.COMMA)));
            }else {
                queryWrapper.eq(HazardReport::getStatus,hazardReport.getStatus());
            }

        }

        if(StringUtils.isNotBlank(hazardReport.getProjectId())){
            queryWrapper.eq(HazardReport::getProjectId,hazardReport.getProjectId());
        }

        if(StringUtils.isNotBlank(hazardReport.getHazardOperation())){
            queryWrapper.eq(HazardReport::getHazardOperation,hazardReport.getHazardOperation());
        }

        if(StringUtils.isNotBlank(hazardReport.getAreaId())){
            queryWrapper.eq(HazardReport::getAreaId,hazardReport.getAreaId());
        }


        if(StringUtils.isNotBlank(hazardReport.getStartDate()) && StringUtils.isNotBlank(hazardReport.getEndDate())){
            queryWrapper.between(HazardReport::getCreatedTime
                    , DateUtil.parseDate(hazardReport.getStartDate()+DateUtil.START_DATA_PATTERN,DateUtil.FULL_TIME_SPLIT_PATTERN)
                    , DateUtil.parseDate(hazardReport.getEndDate()+DateUtil.END_DATA_PATTERN,DateUtil.FULL_TIME_SPLIT_PATTERN));
        }

        queryWrapper.orderByDesc(HazardReport::getCreatedTime);
        Page<HazardReport> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        IPage<HazardReport> reportPage = this.page(page, queryWrapper);
        IPage<HazardReportDto> resultPage = new Page<>();
        List<HazardReport> reportList = reportPage.getRecords();
        //复制至DTO
        List<HazardReportDto> reportDtoList = BeanHelper.copyWithCollection(reportList,HazardReportDto.class);
        if(!CollectionUtils.isEmpty(reportDtoList)){
            //获取ID
            String reportIdList = reportDtoList.stream().map(HazardReportDto::getReportId).collect(Collectors.joining(StringPool.COMMA));
            //根据ID查询对应文件
            HazardReportFile queryFile = new HazardReportFile();
            queryFile.setDeletedFlg(FebsConstant.VALID);
            queryFile.setReportId(reportIdList);
            queryFile.setReportFileType(HazardConstant.HAZARD_REPORT_FILE_TYPE.HAZARD);
            List<HazardReportFile> resultFileList = fileService.findHazardReportFileList(queryFile);

            //获取租户ID
            String tenantIdList = reportDtoList.stream().map(HazardReportDto::getTenantId).collect(Collectors.joining(StringPool.COMMA));
            //根据租户ID查询对应租户
            Tenant queryTenant = new Tenant();
            queryTenant.setTenantId(tenantIdList);
            queryTenant.setDeletedFlg(FebsConstant.VALID);
            List<TenantDto> resultTenantList = tenantService.findTenantList(queryTenant);
            //循环拼接文件信息和租户名称
            reportDtoList.forEach(item->{
                List<HazardReportFile> fileList = resultFileList.stream().filter(file->item.getReportId().equals(file.getReportId())).collect(Collectors.toList());
                item.setFileList(fileList);

                TenantDto tenant = resultTenantList.stream().filter(t -> item.getTenantId().equals(t.getTenantId())).findFirst().get();
                if(ObjectUtils.isNotEmpty(tenant)){
                    item.setTenantName(tenant.getTenantName());
                }
            });
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setRecords(reportDtoList);
        return resultPage;
    }

    /**
     * 查询（所有）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     * @param hazardReport hazardReport
     * @return List<HazardReport>
     */
    @Override
    public List<HazardReport> findHazardReportList(HazardReport hazardReport) {
	    LambdaQueryWrapper<HazardReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HazardReport::getDeletedFlg, 0);
		// TODO 设置查询条件
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author wanghw
    * @date 2024-08-20 09:23:04
    * @param id
    * @return HazardReport
    */
    @Override
    public HazardReportDto findHazardReportById(String id){

        HazardReport report = this.baseMapper.selectById(id);
        if(ObjectUtils.isNotEmpty(report)){
            HazardReportDto dto = new HazardReportDto();
            BeanUtils.copyProperties(report,dto);
            //查询对应隐患文件
            HazardReportFile file = new HazardReportFile();
            file.setReportId(report.getReportId());
            file.setDeletedFlg(FebsConstant.VALID);
            file.setReportFileType(HazardConstant.HAZARD_REPORT_FILE_TYPE.HAZARD);
            List<HazardReportFile> fileList = fileService.findHazardReportFileList(file);
            if(!CollectionUtils.isEmpty(fileList)){
                dto.setFileList(fileList);
            }
            //查询整改文件
            file.setReportFileType(HazardConstant.HAZARD_REPORT_FILE_TYPE.RECTIFICATING);
            List<HazardReportFile> feedbackFileList = fileService.findHazardReportFileList(file);
            if(!CollectionUtils.isEmpty(feedbackFileList)){
                dto.setFeedBackFileList(feedbackFileList);
            }
            //获取租户名称
            Tenant tenant = tenantService.findTenantByTenantId(report.getTenantId());
            if(ObjectUtils.isNotEmpty(tenant)){
                dto.setTenantName(tenant.getTenantName());
            }
            //获取隐患类型名称
            if(StringUtils.isNotBlank(dto.getHazardOperation())){
                HazardTypeOperation typeOperation = hazardTypeOperationService.findHazardTypeOperationById(dto.getHazardOperation());
                if(ObjectUtils.isNotEmpty(typeOperation)){
                    dto.setHazardOperation(typeOperation.getTypeName());
                }

            }
            //判断是否转发审核通过，如果是则获取转发审核信息
            if(HazardConstant.FORWARD_FLG.FORWARD_DONE.equals(dto.getForwardFlg())){
                List<HazardReportAuditRecord> auditRecordList = auditRecordService.list(new LambdaQueryWrapper<HazardReportAuditRecord>()
                        .eq(HazardReportAuditRecord::getReportId,dto.getReportId())
                        .eq(HazardReportAuditRecord::getAuditBusiness, HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.FORWARD)
                        .eq(HazardReportAuditRecord::getDeletedFlg,FebsConstant.VALID));
                if(!CollectionUtils.isEmpty(auditRecordList)){
                    HazardReportAuditRecord auditRecord = auditRecordList.get(0);
                    dto.setForwardAuditCreateBy(auditRecord.getAuditRealName());
                    dto.setForwardAuditReason(auditRecord.getAuditReason());
                    dto.setForwardAuditCreateTime(auditRecord.getCreatedTime());
                    dto.setForwardAuditStatus(auditRecord.getAuditResult());
                }
            }

            //查询 制定计划，整改反馈，审核记录
            HazardReportAuditRecord queryRecord = new HazardReportAuditRecord();
            queryRecord.setReportId(id);
            List<HazardReportAuditRecord> recordList = auditRecordService.findHazardReportAuditRecordList(queryRecord);
            if(!CollectionUtils.isEmpty(recordList)){
                dto.setPlanRecordList(recordList.stream().filter(item->HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.PLAN.equals(item.getAuditBusiness()))
                        .collect(Collectors.toList()));
                dto.setFeedBackRecordList(recordList.stream().filter(item->HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.RECTIFICATION.equals(item.getAuditBusiness()))
                        .collect(Collectors.toList()));
                dto.setAuditRecordList(recordList.stream().filter(item->HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.AUDIT.equals(item.getAuditBusiness()))
                        .collect(Collectors.toList()));
            }

            //查询留言记录
            HazardReportMessage query = new HazardReportMessage();
            query.setReportId(id);
            List<HazardReportMessageDto> messageList = hazardReportMessageService.findHazardReportMessageList(query);
            dto.setMessageList(messageList);

            return dto;
        }else {
            return null;
        }

    }

    /**
     * 新增
     * @author wanghw
     * @date 2024-08-20 09:23:04
     * @param hazardReport hazardReport
     */
    @Override
    @Transactional
    public void createHazardReport(HazardReportDto hazardReport) {
        hazardReport.setCreatedTime(new Date());
        this.save(hazardReport);
        List<HazardReportFile> fileList = hazardReport.getFileList();
        if(!CollectionUtils.isEmpty(fileList)){
            fileList.forEach(i->{
                i.setReportId(hazardReport.getReportId());
                i.setCreatedBy(hazardReport.getCreatedBy());
                i.setCreatedTime(new Date());
                i.setDeletedFlg(FebsConstant.VALID);
                i.setTenantId(hazardReport.getTenantId());
                i.setReportFileType(HazardConstant.HAZARD_REPORT_FILE_TYPE.HAZARD);
            });
            fileService.saveBatch(fileList);
        }

    }

    /**
     * 修改
     * @author wanghw
     * @date 2024-08-20 09:23:04
     * @param hazardReport hazardReport
     */
    @Override
    @Transactional
    public void updateHazardReport(HazardReportDto hazardReport) {
        hazardReport.setUpdatedTime(new Date());
        this.saveOrUpdate(hazardReport);
        //将原文件至失效
        fileService.update(new LambdaUpdateWrapper<HazardReportFile>()
                .eq(HazardReportFile::getReportId,hazardReport.getReportId())
                .eq(HazardReportFile::getDeletedFlg,FebsConstant.VALID)
                .set(HazardReportFile::getDeletedFlg,FebsConstant.INVALID)
                .set(HazardReportFile::getDeletedBy,hazardReport.getUpdatedBy())
                .set(HazardReportFile::getDeletedTime,new Date()));

        //新增新文件
        List<HazardReportFile> fileList = hazardReport.getFileList();
        if(!CollectionUtils.isEmpty(fileList)){
            fileList.forEach(i->{
                i.setReportId(hazardReport.getReportId());
                i.setCreatedBy(hazardReport.getUpdatedBy());
                i.setCreatedTime(new Date());
                i.setDeletedFlg(FebsConstant.VALID);
                i.setTenantId(hazardReport.getTenantId());
                i.setReportFileType(HazardConstant.HAZARD_REPORT_FILE_TYPE.HAZARD);
            });
            fileService.saveBatch(fileList);
        }


    }

    /**
     * 逻辑删除
     * @author wanghw
     * @date 2024-08-20 09:23:04
     * @param hazardReport hazardReport
     * @param hazardReportIds hazardReportIds
     */
    @Override
    @Transactional
    public void deleteHazardReport(HazardReport hazardReport,String hazardReportIds) {
        List<String> list = Arrays.asList(hazardReportIds.split(StringPool.COMMA));
        this.baseMapper.update(hazardReport,new LambdaQueryWrapper<HazardReport>().in(HazardReport::getReportId,list));
	}

    /**
    * 物理删除
    * @author wanghw
    * @date 2024-08-20 09:23:04
    * @param hazardReportIds hazardReportIds
    */
    @Override
    @Transactional
    public void physicallyDeleteHazardReport(String hazardReportIds) {
        List<String> list = Arrays.asList(hazardReportIds.split(StringPool.COMMA));
        LambdaQueryWrapper<HazardReport> wapper = new LambdaQueryWrapper<>();
        wapper.in(HazardReport::getReportId,list);
        this.remove(wapper);
    }

    /**
     * 获取隐患信息编号
     * @param tenantId
     * @return
     */
    @Override
    public String createHazardReportNo(String tenantId,String deptId) {
        StringBuilder no = new StringBuilder();
        Tenant tenant = tenantService.getById(tenantId);
        if(ObjectUtils.isNotEmpty(tenant) && StringUtils.isNotBlank(tenant.getBusinessCode())){
            no.append(tenant.getBusinessCode());
        }
        Dept dept = deptService.findDeptByDeptId(deptId);
        if(ObjectUtils.isNotEmpty(dept)  && StringUtils.isNotBlank(dept.getBusinessCode()) ){
            no.append(dept.getBusinessCode());
        }
        HazardReport hazardReport = this.baseMapper.selectOne(
                new LambdaQueryWrapper<HazardReport>()
                        .ge(HazardReport::getCreatedTime,DateUtil.getCurrentYuanDan())
                        .orderByDesc(HazardReport::getCreatedTime).last("limit 1"));
        no.append(Calendar.getInstance().get(Calendar.YEAR)%2000);
        if(null != hazardReport){
            //在最新的编号上+1
            String currentNewestNo = hazardReport.getReportNo().substring(hazardReport.getReportNo().length()-5,hazardReport.getReportNo().length());
            no.append(String.format("%05d",Integer.parseInt(currentNewestNo)+1));
        }else{
            //创建该公司下第一个事故编号
            no.append(HazardConstant.HAZARD_NO_START_NUM);
        }
        return no.toString();
    }

    /**
     * 提交隐患信息
     * @param hazardReport
     * @param hazardReportId
     */
    @Override
    @Transactional
    public void submitHazardReport(HazardReport hazardReport, String hazardReportId) {
        this.baseMapper.update(hazardReport,new LambdaQueryWrapper<HazardReport>().eq(HazardReport::getReportId,hazardReportId));
        //将审核表中的，制定计划退回记录置为失效
        auditRecordService.update(new LambdaUpdateWrapper<HazardReportAuditRecord>()
                .eq(HazardReportAuditRecord::getDeletedFlg,FebsConstant.VALID)
                .eq(HazardReportAuditRecord::getAuditBusiness,HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.PLAN)
                .eq(HazardReportAuditRecord::getAuditResult,HazardConstant.HAZARD_IS_OR_NO.NO)
                .eq(HazardReportAuditRecord::getReportId,hazardReportId)
                .set(HazardReportAuditRecord::getDeletedFlg,FebsConstant.INVALID)
                .set(HazardReportAuditRecord::getDeletedBy,hazardReport.getUpdatedBy())
                .set(HazardReportAuditRecord::getDeletedTime,new Date()));

    }

    /**
     * 制定计划
     * @param hazardReport
     * @param updateUser
     * @param originStatus  原状态
     */
    @Override
    @Transactional
    public void createHazardReportPlanRecord(HazardReportDto hazardReport, User updateUser ,String originStatus) {
         int updateRow = this.baseMapper.update(hazardReport,new LambdaUpdateWrapper<HazardReport>()
                 .eq(HazardReport::getStatus,originStatus)
                 .eq(HazardReport::getDeletedFlg,FebsConstant.VALID)
                 .eq(HazardReport::getReportId,hazardReport.getReportId()));
        if(updateRow == 1){
            HazardReportAuditRecord record = new HazardReportAuditRecord();
            record.setReportId(hazardReport.getReportId());
            record.setAuditBusiness(HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.PLAN);
            record.setCreatedBy(hazardReport.getUpdatedBy());
            record.setCreatedTime(hazardReport.getUpdatedTime());
            record.setTenantId(hazardReport.getTenantId());
            record.setAuditUserId(updateUser.getUserId());
            record.setAuditRealName(updateUser.getUname());
            record.setAuditReason(hazardReport.getRectificationMeasures());
            if(HazardConstant.HAZARD_STATUS.RECTIFICATION.equals(hazardReport.getStatus())){
                record.setAuditResult(HazardConstant.HAZARD_IS_OR_NO.IS);
            }else if(HazardConstant.HAZARD_STATUS.BACK_PLAN.equals(hazardReport.getStatus())){
                record.setAuditResult(HazardConstant.HAZARD_IS_OR_NO.NO);
            }
            auditRecordService.createHazardReportAuditRecord(record );

            //逻辑删除 违章区域负责人信息
            reportAreaUserService.deleteHazardReportAreaUserByReportId(new HazardReportAreaUser(),hazardReport.getReportId());
            if(HazardConstant.HAZARD_STATUS.RECTIFICATION.equals(hazardReport.getStatus())){
                //批量新增 违章区域负责人
                List<HazardReportAreaUser> areaUsers = getAreaLeader(hazardReport);
                reportAreaUserService.saveBatch(areaUsers);
                //TODO 违章负责人通知
            }


        }

    }

    /**
     * 提交整改反馈信息，整改反馈完成
     * @param hazardReport
     * @param updateUser
     */
    @Override
    @Transactional
    public void submitHazardReportRectificationRecord(HazardReportDto hazardReport, User updateUser) {
        int updateRow = this.baseMapper.update(hazardReport,new LambdaUpdateWrapper<HazardReport>()
                .eq(HazardReport::getDeletedFlg,FebsConstant.VALID)
                .eq(HazardReport::getReportId,hazardReport.getReportId()));
        if(updateRow == 1){
            //新增审核记录
            HazardReportAuditRecord record = new HazardReportAuditRecord();
            record.setReportId(hazardReport.getReportId());
            record.setAuditBusiness(HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.RECTIFICATION);
            record.setCreatedBy(hazardReport.getUpdatedBy());
            record.setCreatedTime(hazardReport.getUpdatedTime());
            record.setTenantId(hazardReport.getTenantId());
            record.setAuditUserId(updateUser.getUserId());
            record.setAuditRealName(updateUser.getUname());
            record.setAuditReason(hazardReport.getRectificationMeasures());
            if(HazardConstant.HAZARD_STATUS.WAITING_AUDIT.equals(hazardReport.getStatus())){
                //提交审核
                record.setAuditResult(HazardConstant.HAZARD_IS_OR_NO.IS);
            }else if(HazardConstant.HAZARD_STATUS.BACK_RECTIFICATION.equals(hazardReport.getStatus())){
                record.setAuditResult(HazardConstant.HAZARD_IS_OR_NO.NO);
            }
            auditRecordService.createHazardReportAuditRecord(record);
            //把之前整改反馈图片之为失效
            fileService.update(new LambdaUpdateWrapper<HazardReportFile>()
                    .eq(HazardReportFile::getReportId,hazardReport.getReportId())
                    .eq(HazardReportFile::getDeletedFlg,FebsConstant.VALID)
                    .eq(HazardReportFile::getReportFileType,HazardConstant.HAZARD_REPORT_FILE_TYPE.RECTIFICATING)
                    .set(HazardReportFile::getDeletedFlg,FebsConstant.INVALID)
                    .set(HazardReportFile::getDeletedTime,new Date())
                    .set(HazardReportFile::getDeletedBy,updateUser.getUserName()));

            List<HazardReportFile> feedBackFileList = hazardReport.getFeedBackFileList();
            if(!CollectionUtils.isEmpty(feedBackFileList)){
                //新增整改反馈照片
                feedBackFileList.forEach(i->{
                    i.setReportId(hazardReport.getReportId());
                    i.setCreatedBy(hazardReport.getUpdatedBy());
                    i.setCreatedTime(new Date());
                    i.setDeletedFlg(FebsConstant.VALID);
                    i.setTenantId(hazardReport.getTenantId());
                    i.setReportFileType(HazardConstant.HAZARD_REPORT_FILE_TYPE.RECTIFICATING);
                });
                fileService.saveBatch(feedBackFileList);
            }
        }
    }

    /**
     * 隐患信息转发
     * @param hazardReport
     */
    @Override
    @Transactional
    public void forwardToHazardReportRectificationRecord(HazardReportDto hazardReport, User updateUser) {
        int updateRow = this.baseMapper.update(hazardReport,new LambdaUpdateWrapper<HazardReport>()
                .eq(HazardReport::getDeletedFlg,FebsConstant.VALID)
                .eq(HazardReport::getReportId,hazardReport.getReportId())
                .eq(HazardReport::getForwardFlg, HazardConstant.FORWARD_FLG.UN_FORWARD));
//        if(updateRow == 1) {
//            //新增审核记录
//            HazardReportAuditRecord record = new HazardReportAuditRecord();
//            record.setReportId(hazardReport.getReportId());
//            record.setAuditBusiness(HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.FORWARD);
//            record.setCreatedBy(hazardReport.getUpdatedBy());
//            record.setCreatedTime(hazardReport.getUpdatedTime());
//            record.setTenantId(hazardReport.getTenantId());
//            record.setAuditUserId(updateUser.getUserId());
//            record.setAuditRealName(updateUser.getUname());
//            record.setAuditReason(hazardReport.getForwardToRemark());
//            auditRecordService.createHazardReportAuditRecord(record);
//        }
    }

    /**
     * 转发隐患信息审核
     * @param hazardReport
     * @param updateUser
     */
    @Override
    @Transactional
    public void auditForwardToHazardReport(HazardReportDto hazardReport, User updateUser) {
        int updateRow = this.baseMapper.update(hazardReport,new LambdaUpdateWrapper<HazardReport>()
                .eq(HazardReport::getDeletedFlg,FebsConstant.VALID)
                .eq(HazardReport::getReportId,hazardReport.getReportId())
                .eq(HazardReport::getForwardFlg, HazardConstant.FORWARD_FLG.WAIT_AUDIT));
        if(updateRow ==1){
            HazardReportAuditRecord record = new HazardReportAuditRecord();
            record.setReportId(hazardReport.getReportId());
            record.setAuditBusiness(HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.FORWARD);
            record.setCreatedBy(hazardReport.getUpdatedBy());
            record.setCreatedTime(hazardReport.getUpdatedTime());
            record.setTenantId(hazardReport.getTenantId());
            record.setAuditUserId(updateUser.getUserId());
            record.setAuditRealName(updateUser.getUname());
            record.setAuditReason(hazardReport.getForwardAuditReason());
            record.setAuditResult(hazardReport.getForwardAuditStatus());
            auditRecordService.createHazardReportAuditRecord(record);
        }
    }

    /**
     * 保存整改反馈信息，整改反馈中
     * @param hazardReport
     * @param updateUser
     */
    @Override
    @Transactional
    public void saveHazardReportRectificationRecord(HazardReportDto hazardReport, User updateUser) {
        int updateRow = this.baseMapper.update(hazardReport,new LambdaUpdateWrapper<HazardReport>()
                .eq(HazardReport::getDeletedFlg,FebsConstant.VALID)
                .eq(HazardReport::getReportId,hazardReport.getReportId()));
        if(updateRow == 1){
            //把之前整改反馈图片之为失效
            fileService.update(new LambdaUpdateWrapper<HazardReportFile>()
                    .eq(HazardReportFile::getReportId,hazardReport.getReportId())
                    .eq(HazardReportFile::getDeletedFlg,FebsConstant.VALID)
                    .eq(HazardReportFile::getReportFileType,HazardConstant.HAZARD_REPORT_FILE_TYPE.RECTIFICATING)
                    .set(HazardReportFile::getDeletedFlg,FebsConstant.INVALID)
                    .set(HazardReportFile::getDeletedTime,new Date())
                    .set(HazardReportFile::getDeletedBy,updateUser.getUserName()));
            List<HazardReportFile> feedBackFileList = hazardReport.getFeedBackFileList();
            if(!CollectionUtils.isEmpty(feedBackFileList)){
                //新增整改反馈图片
                feedBackFileList.forEach(i->{
                    i.setReportId(hazardReport.getReportId());
                    i.setCreatedBy(hazardReport.getUpdatedBy());
                    i.setCreatedTime(new Date());
                    i.setDeletedFlg(FebsConstant.VALID);
                    i.setTenantId(hazardReport.getTenantId());
                    i.setReportFileType(HazardConstant.HAZARD_REPORT_FILE_TYPE.RECTIFICATING);
                });
                fileService.saveBatch(feedBackFileList);
            }
        }
    }

    /**
     * 隐患信息审核
     * @param hazardReport
     * @param updateUser
     */
    @Override
    @Transactional
    public void saveHazardReportAuditRecord(HazardReportDto hazardReport, User updateUser) {
        int updateRow = this.baseMapper.update(hazardReport,new LambdaUpdateWrapper<HazardReport>()
                .eq(HazardReport::getStatus,HazardConstant.HAZARD_STATUS.WAITING_AUDIT)
                .eq(HazardReport::getDeletedFlg,FebsConstant.VALID)
                .eq(HazardReport::getReportId,hazardReport.getReportId()));
        if(updateRow == 1){
            HazardReportAuditRecord record = new HazardReportAuditRecord();
            record.setReportId(hazardReport.getReportId());
            record.setAuditBusiness(HazardConstant.HAZARD_AUDIT_BUSINESS_TYPE.AUDIT);
            record.setCreatedBy(updateUser.getUserName());
            record.setCreatedTime(hazardReport.getUpdatedTime());
            record.setTenantId(hazardReport.getTenantId());
            record.setAuditUserId(updateUser.getUserId());
            record.setAuditRealName(updateUser.getUname());
            record.setAuditReason(hazardReport.getAuditRemark());
            if(HazardConstant.HAZARD_STATUS.WAITING_ISSUANCE.equals(hazardReport.getStatus())){
                //审核通过
                record.setAuditResult(HazardConstant.HAZARD_IS_OR_NO.IS);
            }else if(HazardConstant.HAZARD_STATUS.BACK_AUDIT.equals(hazardReport.getStatus())){
                //审核退回
                record.setAuditResult(HazardConstant.HAZARD_IS_OR_NO.NO);
            }
            auditRecordService.createHazardReportAuditRecord(record );
        }
    }

    /**
     * 隐患信息签发
     * @param hazardReport
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveHazardReportAppealRecord(HazardReportDto hazardReport) throws FebsException{
        int updateRow = this.baseMapper.update(hazardReport,new LambdaUpdateWrapper<HazardReport>()
                .eq(HazardReport::getStatus,HazardConstant.HAZARD_STATUS.WAITING_ISSUANCE)
                .eq(HazardReport::getDeletedFlg,FebsConstant.VALID)
                .eq(HazardReport::getReportId,hazardReport.getReportId()));
        // 扣积分，插记录
        User byId = userService.findById(hazardReport.getLeaderId());
        if(null != byId) {
            // 减用户积分
            User u = new User();
            u.setUpdatedBy(hazardReport.getUpdatedBy());
            u.setModifyTime(new Date());
            u.setTotalScore(hazardReport.getBonusPoints() * -1);
            u.setUserId(hazardReport.getLeaderId());
            boolean success = userService.updateScore(u);
            if (!success) {
                throw new FebsException("【" + u.getUserName() + "】用户积分更新失败，请联系管理员！");
            }

            // 用户积分使用记录
            BaseUserScoreRecord baseUserScoreRecord = new BaseUserScoreRecord();
            baseUserScoreRecord.setTenantId(hazardReport.getTenantId());
            baseUserScoreRecord.setUserId(hazardReport.getLeaderId());
            baseUserScoreRecord.setRealName(hazardReport.getLeaderName());
            baseUserScoreRecord.setUserNo(hazardReport.getLeaderNo());
            baseUserScoreRecord.setDeptId(hazardReport.getLeaderDeptId());
            baseUserScoreRecord.setDeptName(hazardReport.getLeaderDeptName());
            baseUserScoreRecord.setDataSource("3");
            baseUserScoreRecord.setDataTargetId(hazardReport.getReportId());
            baseUserScoreRecord.setOperateType("1");
            baseUserScoreRecord.setOperateDate(new Date());
            baseUserScoreRecord.setOperateScore(hazardReport.getBonusPoints());
            baseUserScoreRecord.setBeforeScore(byId.getTotalScore());
            baseUserScoreRecord.setAfterScore(byId.getTotalScore() + hazardReport.getBonusPoints());
            baseUserScoreRecord.setCreatedBy(hazardReport.getUpdatedBy());
            baseUserScoreRecord.setCreatedTime(new Date());
            boolean save1 = baseUserScoreRecordService.save(baseUserScoreRecord);
            if (!save1) {
                throw new FebsException("用户积分使用记录更新失败，请联系管理员！");
            }
        }
    }

    /**
     * 删除隐患信息
     * @param hazardReport
     */
    @Override
    @Transactional
    public void deleteHazardReportRecord(HazardReportDto hazardReport) {
        this.baseMapper.update(hazardReport,new LambdaUpdateWrapper<HazardReport>()
                .eq(HazardReport::getStatus,HazardConstant.HAZARD_STATUS.BACK_PLAN)
                .eq(HazardReport::getDeletedFlg,FebsConstant.VALID)
                .eq(HazardReport::getReportId,hazardReport.getReportId()));
    }

    /**
     * 恢复已删除数据
     * @param id
     */
    @Override
    @Transactional
    public void redoHazardReportRecord(String id) {
        HazardReport report = new HazardReport();
        report.setReportId(id);
        report.setStatus(HazardConstant.HAZARD_STATUS.UPLOAD);
        report.setUpdatedTime(new Date());
        this.baseMapper.update(report,new LambdaUpdateWrapper<HazardReport>()
                .eq(HazardReport::getStatus,HazardConstant.HAZARD_STATUS.DELETE)
                .eq(HazardReport::getDeletedFlg,FebsConstant.VALID)
                .eq(HazardReport::getReportId,id));
    }

    /**
     * 统计用户当天提交的隐患
     * @param userName
     * @return
     */
    @Override
    public int countTodayByUserName(String userName) {
        HazardReport queryHa = new HazardReport();
        queryHa.setCreatedBy(userName);
        queryHa.setCreatedTime(DateUtil.getCurrentDay());
        List<String> statusList = Arrays.asList(HazardConstant.HAZARD_STATUS.PLAN,
                HazardConstant.HAZARD_STATUS.RECTIFICATION,
                HazardConstant.HAZARD_STATUS.RECTIFICATING,
                HazardConstant.HAZARD_STATUS.WAITING_AUDIT,
                HazardConstant.HAZARD_STATUS.WAITING_ISSUANCE,
                HazardConstant.HAZARD_STATUS.ISSUANCED,
                HazardConstant.HAZARD_STATUS.BACK_PLAN,
                HazardConstant.HAZARD_STATUS.BACK_RECTIFICATION,
                HazardConstant.HAZARD_STATUS.BACK_AUDIT
                );
        String statusStr = statusList.stream().collect(Collectors.joining(StringPool.COMMA));
        queryHa.setStatus(statusStr);
        List<HazardReport> hazardReportList = this.findHazardReportList(queryHa);
        if(!CollectionUtils.isEmpty(hazardReportList)){
            return hazardReportList.size();
        }
        return 0;
    }


    /**
     * 组装违章区域排班负责人信息
     * @param hazardReport
     * @return
     */
    private List<HazardReportAreaUser> getAreaLeader(HazardReportDto hazardReport){
        List<HazardReportAreaUser> areaUsers = new ArrayList<>();
        BaseAreaSchedulingDto queryDto = new BaseAreaSchedulingDto();
        queryDto.setStartDate(DateUtil.getDateFormat(DateUtil.getCurrentDay(),DateUtil.YYYY_MM_DD_PATTERN));
        queryDto.setEndDate(DateUtil.getDateFormat(DateUtil.getCurrentDay(),DateUtil.YYYY_MM_DD_PATTERN));
        queryDto.setAreaId(hazardReport.getAreaId());
        LocalTime now = LocalDateTime.now().toLocalTime();

        List<BaseAreaSchedulingDto> schedulingDtos = schedulingService.findBaseAreaSchedulingList(queryDto);
        if(!CollectionUtils.isEmpty(schedulingDtos)){
            schedulingDtos.forEach(item->{
                if(checkSchedulingTime(now,item)){
                    HazardReportAreaUser areaUser = new HazardReportAreaUser();
                    areaUser.setReportId(hazardReport.getReportId());
                    areaUser.setTenantId(hazardReport.getTenantId());
                    areaUser.setAreaLeaderId(item.getUserId());
                    areaUser.setAreaLeaderNo(item.getUserNo());
                    areaUser.setAreaLeaderName(item.getUserName());
                    areaUser.setCreatedBy(hazardReport.getPlanFormulateName());
                    areaUser.setCreatedTime(new Date());
                    areaUser.setDeletedFlg(FebsConstant.VALID);
                    areaUsers.add(areaUser);
                }

            });
        }
        return areaUsers;
    }

    /**
     * 校验当前事件是否属于排班事件段范围内
     * @param now 当前时间
     * @param dto 所属排班
     * @return
     */
    private boolean checkSchedulingTime(LocalTime now, BaseAreaSchedulingDto dto){
        String schedulingTime = dto.getSchedulingTime();
        if(StringUtils.isBlank(schedulingTime)){
            return false;
        }
        //06:00 - 07:59
        String[] times = schedulingTime.split(StringPool.DASH);
        LocalTime startTime = LocalTime.parse(times[0].trim()+":00");
        LocalTime endTime = LocalTime.parse(times[1].trim()+":59");

        if(now.isBefore(startTime)){
            return false;
        }

        if(now.isAfter(endTime)){
            return false;
        }
        return true;
    }


    /**
     * 统计本年度 审核通过的 该人员的 违章次数，罚款金额以及扣除分数
     *
     * @return
     */
    @Override
    public Map<String, Object> countYearByUserName(String userName) {
        QueryWrapper<HazardReport> wrapper = new QueryWrapper<>();
        wrapper.select("CASE WHEN SUM(bonus_points)>0 THEN SUM(bonus_points) ELSE '0' end as bonusPoints");
        List<String> statusList = Arrays.asList(HazardConstant.HAZARD_STATUS.WAITING_ISSUANCE,
                HazardConstant.HAZARD_STATUS.ISSUANCED);
        wrapper.in("status",statusList);
        wrapper.eq("created_by",userName);
        wrapper.ge("created_time", DateUtil.getCurrentYuanDan());
        return this.getMap(wrapper);
    }


}
